package ltd.dujiabao.zookeeper.watcher;

import org.apache.log4j.Logger;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

import java.util.concurrent.CountDownLatch;

/**
 * @author : DuJiabao
 * @Project : zookeeper
 * @Time : 2021/5/2 21:11
 * @Desc :
 */
public class ZKConnectionWatcher implements Watcher {

  private CountDownLatch countDownLatch = null;
  private static final Logger log = Logger.getLogger(ZKConnectionWatcher.class);

  public ZKConnectionWatcher() {
  }

  public ZKConnectionWatcher(CountDownLatch countDownLatch) {
    this.countDownLatch = countDownLatch;
  }

  @Override
  public void process(WatchedEvent watchedEvent) {
    if (watchedEvent.getType() == Event.EventType.None) {   // 说明没有发生除了连接问题以外的事件
      switch (watchedEvent.getState()) {
        case SyncConnected:
          log.info("客户端与服务器正常连接");
          if (this.countDownLatch != null) this.countDownLatch.countDown();
          break;
        case Disconnected:
          log.info("客户端与服务器断开连接");
          break;
        case Expired:
          log.info("会话SESSION超时");
          break;
        case AuthFailed:
          log.info("身份认证失败");
          break;
      }
    }
  }

  public void setCountDownLatch(CountDownLatch countDownLatch) {
    this.countDownLatch = countDownLatch;
  }
}
